import $H from '@/utils/request.js';

class chat {
	constructor(arg) {
		this.url = arg.url;
		this.isOnline = false;
		this.socket = null;
		let user = window.localStorage.getItem("user")
		this.user = user ? JSON.parse(user) : {},
			this.TO = {};
		if (this.user.token) {
			this.connect();
		} else {
			this.close()
		}
	}
	connect() {
		let socket = uni.connectSocket({
			url: "ws://127.0.0.1:7001/ws?token=" + this.user.token,
			complete: () => {

			}
		})
		this.socket = socket;
		this.socket.onOpen(() => {
			this.onOpen()
		})
		this.socket.onMessage((res) => {
			this.onMessage(res)
		})
		this.socket.onClose(() => {
			this.onClose()
		})
		this.socket.onError((res) => {
			this.onError()
		})
	}
	onOpen() {
		this.isOnline = true
		console.log("socket连接成功")
	}
	onClose() {
		this.isOnline = false
		this.socket = null
		console.log("socket连接关闭")

	}
	onMessage(res) {
		console.log(res, "监听数据")
		let data = JSON.parse(res.data);
		if (data.msg == 'fail') {
			return uni.showToast({
				title: data.data,
				icon: 'none'
			})
		}
		this.handleOnMessage(data.data)
	}
	handleOnMessage(message) {
		let {
			data
		} = this.addmessagedetail(message, false)
		this.updateChatList(data, false)
		uni.$emit("onMessage", data)
	}
	onError() {
		this.isOnline = false
		this.socket = null
		console.log("socket连接错误")

	}
	getName() {
		console.log("name")
		if (this.socket) {
			console.log(this.socket)
			this.socket.close()
			console.log('close')
		}
	}
	getClist() {
		console.log("chatlist");
		let key = `chatlist_${this.user.id}`;
		return this.getStorage(key)
	}
	createchatobject(detail) {
		console.log("ddde")
		this.TO = detail
		console.log(this.TO, "TO")
	}
	destroychatobject() {
		this.TO = {}
	}
	formatSendData(params) {

		return {
			id: 0, // 唯一id，后端生成，用于撤回指定消息
			from_avatar: this.user.avatar ? this.user.avatar :
				'https://profile-avatar.csdnimg.cn/3365568353cd44c2acf217ab8b6345f9_weixin_47365777.jpg!1', // 发送者头像
			from_name: this.user.nickname || this.user.username, // 发送者昵称
			from_id: this.user.id, // 发送者id
			to_id: params.to_id || this.TO.id, // 接收人/群 id
			to_name: params.to_name || this.TO.nickname, // 接收人/群 名称
			to_avatar: params.to_avatar || this.TO.avatar, // 接收人/群 头像
			chat_type: params.chat_type || this.TO.chat_type, // 接收类型
			type: params.type, // 消息类型
			data: params.data, // 消息内容
			options: params.options ? params.options : {}, // 其他参数
			create_time: (new Date()).getTime(), // 创建时间
			isremove: 0, // 是否撤回
			sendStatus: params.sendStatus ? params.sendStatus : "pending" // 发送状态，success发送成功,fail发送失败,pending发送中
		}
	}
	//发送消息
	send(message) {

		console.log(message, "::")
		return new Promise(async (result, reject) => {
			let {
				data,
				k
			} = this.addmessagedetail(message, true)

			console.log(message, "::")
			console.log(message.id, "::")
			//更新会话列表
			this.updateChatList(message)
			if (!this.checkOnline()) return reject("未上线")
			$H.post("send", {
				to_id: this.TO.id,
				chat_type: this.TO.chat_type,
				type: message.type,
				data: message.data,

			}).then(res => {
				console.log(res, "res")

				message.id = res.id;
				message.sendStatus = 'success'
				console.log(message.id, "messid")
				//更新指定历史记录
				this.updatemessage(message, k)
				result(res)
			}).catch(err => {
				message.sendStatus = 'fail'
				//更新指定历史记录
				this.updatemessage(message, k)
				reject(err)
			})
		})

	}
	checkOnline() {
		if (!this.isOnline) {
			this.reconnectConfirm()
			return false
		}
		return true
	}
	reconnectConfirm() {
		uni.showModal({
			content: '你已经断线，是否重新连接？',
			confirmText: "重新连接",
			success: (res) => {
				if (res.confirm) {
					this.connect()
				} else if (res.cancel) {

				}
			}
		});
	}
	updateChatList(message, isSend = true) {

		//获取本地存储会话列表
		let list = this.getClist();
		//判断是否在线
		let iscurrentChat = false;
		//接收人id
		let id = 0;
		let avatar = ""
		let name = "";
		if (message.chat_type === 'user') {
			//聊天对象是否存在
			if (!this.TO) {
				iscurrentChat = false
			} else {
				iscurrentChat = isSend ? this.TO.id == message.to_id : this.TO.id == message.from_id

			}
			id = isSend ? message.to_id : message.from_id
			avatar = isSend ? message.to_avatar : message.from_avatar
			name = isSend ? message.to_name : message.from_name
		} else {

		}

		let index = list.findIndex(item => {
			console.log(item, id, "item")
			return item.chat_type === message.chat_type && item.id === id
		})
		console.log(index, "index")
		let data = isSend ? message.data : `${message.from_name}:${message.data}`
		//会话不存在就创建
		let noreadnum = (isSend | iscurrentChat) ? 0 : 1
		if (index === -1) {

			let chatItem = {
				id, // 接收人/群 id
				chat_type: message.chat_type, // 接收类型 user单聊 group群聊
				avatar, // 接收人/群 头像
				name, // 接收人/群 昵称
				update_time: (new Date()).getTime(), // 最后一条消息的时间戳
				data, // 最后一条消息内容
				type: message.type, // 最后一条消息类型
				noreadnum, // 未读数
				istop: false, // 是否置顶
				shownickname: false, // 是否显示昵称
				nowarn: false, // 消息免打扰
				strongwarn: false, // 是否开启强提醒
			}
			if (message.chat_type == 'group') {
				chatItem = {
					...chatItem,
					user_id: message.group.user_id, // 群管理员id
					remark: "", // 群公告
					invite_confirm: 1, // 邀请确认
				}
			}
			list.unshift(chatItem)
			console.log(list)
		} else {
			console.log("更新会话")
			//存在，更新会话
			//拿到最新会话
			let item = list[index]
			//更新最后一条会话的内容和时间
			item.update_time = (new Date()).getTime()
			item.data = data
			item.type = message.type
			item.noreadnum += noreadnum
			//置顶会话
			list = this.listTofirst(list, index)

		}
		//存储
		let key = `chatlist_${this.user.id}`
		this.setStorage(key, list);
		//更新未读数
		this.updateBadge(list)
		console.log(123333, "33");
		//通知更新vuex中的会话列表
		uni.$emit('onUpdateChatList', list)
		uni.$on("onUpdateChatList", (list) => {
			console.log("list监听", list)
		})
		return list

	}
	async updateBadge(list = false) {
		console.log(12333, "4");
		list = list ? list : this.getClist();
		let total = 0;
		list.forEach(el => {
			total += el.noreadnum
		})
		console.log(total, "tttoral");
		console.log(total, "tttoral");
		uni.$emit('totalNoreadnum', total)
		if (total > 0) {
			return uni.setTabBarBadge({
				index: 0,
				text: total <= 99 ? total.toString() : "99+"
			})

			// uni.$emit('totalNoreadnum', total)

		} else {
			uni.removeTabBarBadge({
				index: 0
			})
		}
		
		// return total
		// uni.$emit('totalNoreadnum', total)

	}
	listTofirst(arr, index) {
		console.log("listtofirst")
		if (index != 0) {
			arr.unshift(arr.splice(index, 1)[0])
		}
		return arr


	}
    async readchatItem(id,chat_type){
		console.log(123,"4");
		let list=this.getChatlist();
		let index=list.findIndex(item=>item.id === id && item.chat_type===chat_type);
		if(index!==-1){
			list[index].noreadnum=0;
			let key=`chatlist_${this.user.id}`
			this.setStorage(key,list)
			this.updateBadge()
		}
	}
	getchatListItem(id,chat_type){
		let list=this.getChatlist();
		let index=list.findIndex(item=>item.id === id && item.chat_type===chat_type);
		if(index!==-1){
			return list[index]
		}
		return false
	}
	getChatlist1() {
		console.log(1233);
	}
	getChatlist() {
		let key = `chatlist_${this.user.id}`;
		return this.getStorage(key)
	}
	//更新聊天记录
	async updatemessage(message, k, isSend = true) {

		let id = isSend ? message.to_id : message.from_id;
		let key = `chatDetail_${this.user.id}_${message.chat_type}_${id}`
		let list = this.getChatDetail(key)
		//根据k查找对应聊天记录
		let index = list.findIndex(item => item.k === k);
		if (index === -1) return;
		list[index] = message
		this.setStorage(key, list)
	}
	//添加聊天记录
	addmessagedetail(message, isSend = true) {
		console.log(message, "message")
		//key chatDetail_当前用户id_会话类型_接收人id
		let id = isSend ? message.to_id : message.from_id;
		let key = `chatDetail_${this.user.id}_${message.chat_type}_${id}`
		let list = this.getChatDetail(key)
		console.log("原来的聊天记录", list)
		message.k = "k" + list.length;
		list.push(message);
		this.setStorage(key, list);
		return {
			data: message,
			k: message.k
		}
	}
	//获取原来的聊天记录
	getChatDetail(key = false) {
		key = key ? key : `chatDetail_${this.user.id}_${this.TO.chat_type}_${this.TO.id}`
		return this.getStorage(key)
	}
	getStorage(key) {
		let list = window.localStorage.getItem(key);
		return list ? JSON.parse(list) : [];
	}
	setStorage(key, value) {
		return window.localStorage.setItem(key, JSON.stringify(value))
	}
	close() {
		if (this.socket) {
			console.log(this.socket)
			this.socket.close()
			console.log('close')
		}
	}
}
export default chat
